package xuedou.skymoni.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;



public class DBConnection {
	private Connection conn = null;
    private InitialContext ctx = null;	
	private DataSource ds = null;   //数据源
	

	public Connection getConnection() {

		try {
			
				//初始上下文
//				ctx = new InitialContext();
				//数据源
//				ds=(DataSource)ctx.lookup("java:comp/env/MyDatabaseSource");
				//从数据源里取链接
			    conn =ConnectionManager.getConnection();	
			  
			//conn = DriverManager.getConnection(serverUrl, databaseUser,password);
			if(null!=conn) {
			
				Logger.getLogger(DBConnection.class).info("已经建立链接");
			}
		} catch (Exception e) {
			e.printStackTrace();
			Logger.getLogger(DBConnection.class).warn(e.toString());
		}
		return conn;
	}

	/*
	 * 关闭连接
	 */
	public void closeCon(ResultSet rs, PreparedStatement ps, Connection conn) {

		try {   if (rs != null) { rs.close(); } } 
		catch (SQLException e2) { 
			Logger.getLogger(DBConnection.class).warn(e2.toString());
			e2.printStackTrace();
			}
		
		/*--------finally2----------*/
		finally
		{
			try {   if (ps!= null) { ps.close();} } 
			catch (SQLException e3) { 
				Logger.getLogger(DBConnection.class).warn(e3.toString());
				e3.printStackTrace();
				}
			
			/*---finally3----*/
			finally
			{
			try { if (conn != null) { conn.close();} } 
			catch (SQLException e4) { 
				Logger.getLogger(DBConnection.class).warn(e4.toString());
				e4.printStackTrace();
				}
			}
			/*---finally3 End----*/
		
			
			try {
				if(conn.isClosed()){
					//Logger.getLogger(DBConnection.class).info("已成功释放链接资源.");
				} else {
					Logger.getLogger(DBConnection.class).warn("资源没有释放!");
				}
			} catch (SQLException e) {
				e.printStackTrace();
				Logger.getLogger(DBConnection.class).warn(e.toString());
			}
			
		}
	}
}
